Converting an array to hash using Hash::[] constructor

The Hash::[] constructor method creates a hash directly from an array where each pair of elements in the array is treated as a key-value pair.

Syntax:

Hash[*array]

Example: In this example,we convert an array into a hash , where each element in the array is transformed into a key-value pair using Hash::[] constructor

Ruby
# Define an array with elements representing key-value pairs
array = [:a, 1, :b, 2, :c, 3]

# Convert an array into a hash Using Hash::[] constructor
# Convert the array directly into a hash using the Hash::[] constructor
hash = Hash[*array]
# Output the resulting hash
puts hash.inspect  # Output: {:a=>1, :b=>2, :c=>3}

Output
{:a=>1, :b=>2, :c=>3}

How to convert Array to Hash in Ruby?

In this article, we will discuss how to convert an array to a hash in Ruby. Converting an array to a hash can be useful when we have data in an array format and need to organize it into key-value pairs for easier access and manipulation.

Table of Content

  • Converting array to hash using Hash::[] constructor
  • Converting array to hash using Array#each_slice
  • Converting array to hash using Hash#[] with a block

Similar Reads

Converting an array to hash using Hash::[] constructor

The Hash::[] constructor method creates a hash directly from an array where each pair of elements in the array is treated as a key-value pair....

Converting array to hash using Array#each_slice

Array#each_slice method allows to iterate over the array in chunks where each chunk contains two elements representing a key-value pair.Then, using the Hash::[] constructor, we can convert these pairs into a hash....

Converting array to hash using Hash#[] with a block

In this method we iterate over the array and processes each element individually. Then we can specify a block where you define how each element should be converted into a key-value pair....